﻿using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

using Google.GData.Photos;
using Google.GData.Extensions.MediaRss;

namespace McePicasa
{
    class PicasaAPI
    {
        private PicasaAPI() { } //For FxCop only

        /*
        public static PicasaService PicasaService
        {
            get { return PicasaAPI.picasaService; }
            set { PicasaAPI.picasaService = value; }
        }
         * */

        public static PicasaFeed GetUserAlbumFeed(string userID)
        {
            AlbumQuery query = new AlbumQuery();
            query.Uri = new Uri(PicasaQuery.CreatePicasaUri(userID));

            try
            {
                PicasaFeed picasaFeed = picasaService.Query(query);
                if (picasaFeed != null && picasaFeed.Entries.Count > 0)
                {
                    return picasaFeed;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception e)
            {
                throw new PicasaException(e);
            }
        }

        public static PicasaFeed GetAlbumPhotoFeed(string albumUrl)
        {
            PhotoQuery query = new PhotoQuery(albumUrl);
            PicasaFeed photoFeed = picasaService.Query(query);

            if (photoFeed != null && photoFeed.Entries.Count > 0)
            {
                return photoFeed;
            }
            else
            {
                return null;
            }
        }

        public static string FindLargestThumbnail(ThumbnailCollection collection)
        {
            MediaThumbnail largest = null;
            int width = 0;
            foreach (MediaThumbnail thumb in collection)
            {
                int iWidth = int.Parse(thumb.Attributes["width"] as string, CultureInfo.CurrentCulture);
                if (iWidth > width)
                {
                    width = iWidth;
                    largest = thumb;
                }
            }
            return largest.Attributes["url"] as string;
        }

        public static bool SaveImage(string url, string filename)
        {
            try
            {
                /* 20080523: We have problem with this code, image cannot be downloaded
                Stream stream = picasaService.Query(new Uri(url));
                FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
                BinaryWriter w = new BinaryWriter(fs);
                char[] buffer = new char[1024];
                int iRead = 0;
                int iOffset = 0;
                while ((iRead = stream.Read(buffer, 0, 1024)) > 0)
                {
                    w.Write(buffer, 0, iRead);
                    iOffset += iRead;
                }
                if (iOffset == 0) return false;
                w.Close();
                fs.Close();
                return true;
                 * */

                //=> So we try to use this new simple code:
                WebClient wc = new WebClient();
                wc.DownloadFile(url, filename);
                return true;
            }

            catch (System.Net.WebException e)
            {
                Log.LogIt("SaveImage, System.Net.WebException: " + e.Message);
                return false;
            }

            catch (Exception e)
            {
                Log.LogIt("SaveImage, Exception: " + e.Message);
                throw new PicasaException("SaveImage, Exception: " + e.Message);
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public static void TrackUser()
        {
            string url = "http://www.structuretoobig.com/map/getmap.aspx?userid=c2cfd3f7-7ff7-4af7-916f-383400579a60&size=thumb";
            try
            {
                /* 20080523: Bug, mentioned above in SaveImage(...)
                Stream stream = picasaService.Query(
                    new Uri(url));
                byte[] buffer = new byte[1024];
                int iRead = 0;
                int iOffset = 0;
                while ((iRead = stream.Read(buffer, 0, 1024)) > 0)
                {                    
                    iOffset += iRead;
                }
                stream.Dispose();
                 * */
                WebClient wc = new WebClient();
                wc.DownloadData(url);
                wc.Dispose();// We do not really need to do this
            }
            catch (Exception e)
            {
                Global.MsgBox(e.Message, 3);
                Log.LogIt("TrackUser, Exception: " + e.Message);
            }
        }

        /*
        static object syncObj = new object();
        static MethodInfo fromStreamMethodInfo = null;
        static Microsoft.MediaCenter.UI.Image im = new Microsoft.MediaCenter.UI.Image("");
        public static Microsoft.MediaCenter.UI.Image ImageFromStream(Stream stream)
        {
            try
            {
                if (fromStreamMethodInfo == null)
                {
                    lock (syncObj)
                    {
                        MethodInfo[] mis = typeof(Microsoft.MediaCenter.UI.Image).GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
                        foreach (MethodInfo mi in mis)
                        {
                            ParameterInfo[] pis = mi.GetParameters();
                            if (mi.Name == "FromStream" && pis.Length == 2)
                            {
                                if (pis[0].ParameterType == typeof(String) && pis[1].ParameterType == typeof(Stream))
                                {
                                    fromStreamMethodInfo = mi;
                                }
                            }
                        }
                    }
                }
                return (Microsoft.MediaCenter.UI.Image)fromStreamMethodInfo.Invoke(im, new object[] { null, stream });
            }
            catch (Exception e)
            {
                McePicasa.Application.Current.MessageBox(e.Message.ToString(), e.ToString());
                return null;
            }
        }
         * */
        static private PicasaService picasaService = new PicasaService("McePicasa");
    }
}
